<template>
  <view>
    <uv-navbar title="离线任务统计" auto-back placeholder>
      <template v-if="tabStatus == 1" #right>
        <uv-icon
          :name="iconFunnel"
          label="筛选"
          label-color="#4EA770"
          label-size="28rpx"
          @click="rightClick"
        />
      </template>
    </uv-navbar>
    <g-tabs :tabs="tabs" :active="tabStatus" status-bar @change="changeTab" />
    <view v-for="(item, index) in dataList" :key="index" class="offline-task-item">
      <view
        :class="`offline-task-item-status offline-task-item-status-${
          item.offlineStatus || 0
        }`"
      >
        <image :src="statusList[item.offlineStatus || 0].icon" mode="scaleToFill" />
        {{ statusList[item.offlineStatus || 0].label }}
      </view>
      <view class="offline-task-item-top">
        <view class="offline-task-item-title">{{ item.deviceName || "-" }}</view>
        <view>检查项：{{ item.deviceItemName || "-" }}</view>
        <view>完成数量：{{ item.inspectCount || 0 }}</view>
        <view>时间：{{ item.completeTime || "-" }}</view>
        <view>楼栋：{{ item.buildingName || "-" }}</view>
        <view>楼层：{{ item.buildingFloorName || "-" }}层</view>
        <view v-if="tabStatus == 2">失败原因：{{ item.failReason || "-" }}</view>
      </view>
      <view
        v-if="item.offlineStatus == 4"
        class="offline-task-item-btn"
        @click="handleSubmit(item)"
      >
        {{ item.sumbiting ? "上传中" : "重新提交" }}
      </view>
    </view>
    <uv-empty
      v-if="dataList.length === 0"
      :custom-style="{ padding: '10vh 0' }"
      :icon="empty"
      text="暂无记录"
    />
    <uv-load-more v-else :status="moreStatus" :height="30" />
    <uv-popup ref="popupRef" mode="right" z-index="980" closeable>
      <view class="popup-content">
        <uv-status-bar />
        <uv-text
          text="数据筛选"
          color="#757575"
          size="28rpx"
          line-height="100rpx"
          margin="auto 30rpx"
        />
        <uv-text
          text="自定义时间段"
          color="#757575"
          size="28rpx"
          line-height="80rpx"
          margin="auto 30rpx"
        />
        <view class="date-box" @click="handleCalendar">
          <uv-icon name="clock" color="#BDBDBD" size="28rpx" />
          <view class="date"> {{ queryParams.completeTime || "选择时间范围" }} </view>
        </view>
        <view class="row-bottom">
          <uv-button text="重置" @click="resetQuery" />
          <uv-button
            text="确定"
            color="#fff"
            :custom-style="{
              background: '#4EA770',
            }"
            @click="handleQuery"
          />
        </view>
      </view>
    </uv-popup>
    <uv-calendars
      ref="calendarsRef"
      :round="0"
      color="#4EA770"
      confirm-color="#4EA770"
      :date="queryParams.beginTime"
      @confirm="confirmDate"
    />
    <uv-modal
      ref="fristRef"
      title="状态说明"
      :content="`超过正常数量：仅录入剩余数量 任务完成
        已被完成： 本次提交任务已被其他人完成
        完成：提交任务被成功提交
        失败：任务提交失败 请重新录入
        待提交：待恢复网络后提交`"
      confirm-color="#4EA770"
    />
  </view>
</template>
<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { onLoad, onReachBottom } from "@dcloudio/uni-app";
import { recordAdd, recordList } from "@/request/task.js";
import { commonUpload, checkNetwork } from "@/request/common.js";
import EventBus from "@/request/eventBus.js";
import iconFunnel from "@/static/icon_funnel.png";
import iconTask0 from "@/static/order/icon_task0.png";
import iconTask1 from "@/static/order/icon_task1.png";
import iconTask2 from "@/static/order/icon_task2.png";
import iconTask3 from "@/static/order/icon_task3.png";
import iconTask4 from "@/static/order/icon_task4.png";
import empty from "@/static/empty.png";

const tabStatus = ref(0); // 状态 0待提交 1完成 2失败
const tabs = ref([
  // tab列表
  { label: "待提交", badge: { value: 0 } },
  { label: "完成", badge: { value: 0 } },
  { label: "失败", badge: { value: 0 } },
]);
const fristRef = ref(); // 提示弹窗ref
const queryParams = reactive({
  subPlanId: "", // 项目id
  completeTime: "", // 时间
  isOffline: 1, // 是否离线 0否 1是
  pageNum: 1, // 当前页码
  pageSize: 10, // 每页数量
});
const offlineMode = ref(false); // 离线模式
const dataList = ref([]); // 列表数据
const total = ref(0); // 总数
const popupRef = ref(); // 弹出层ref
const calendarsRef = ref(); // 日历组件ref
const moreStatus = ref("loadmore"); // 加载更多
const statusList = ref([
  { value: 0, label: "待提交", icon: iconTask0 },
  { value: 1, label: "完成", icon: iconTask1 },
  { value: 2, label: "任务已完成", icon: iconTask2 },
  { value: 3, label: "超过正常数量", icon: iconTask3 },
  { value: 4, label: "失败", icon: iconTask4 },
]);

onLoad((e) => {
  queryParams.maintenanceSubPlanId = e.subPlanId;
  getList();
});

onMounted(() => {
  EventBus.on("offlineChange", updateOffline);
  // 首次弹窗提示
  let list = uni.getStorageSync("offline-task-list");
  if (list && list.frist) {
    fristRef.value.open();
    list.frist = false;
    uni.setStorageSync("offline-task-list", list);
  }
  uni.$on("network-change", (status) => {
    offlineMode.value = status == "none";
    if (status != "none" && tabStatus.value == 1) {
      handleQuery();
    }
  });
});

onReachBottom(() => {
  if (tabStatus.value == 1 && offlineMode.value) return;
  if (moreStatus.value == "nomore") return;
  queryParams.pageNum += 1;
  getList();
});

onBeforeUnmount(() => {
  EventBus.off("offlineChange", updateOffline);
});

// 更新离线列表
const updateOffline = (data) => {
  if (data) getList(true);
};

// tab切换
const changeTab = async (val) => {
  tabStatus.value = val.index;
  queryParams.pageNum = 1;
  dataList.value = [];
  if (tabStatus.value == 1) {
    const network = await checkNetwork(); // 检查网络
    offlineMode.value = network == "none";
    if (network == "none") {
      uni.showToast({
        title: "当前为离线模式，请恢复网络再试",
        duration: 1500,
        icon: "none",
      });
      return;
    }
  }
  getList();
};

// 打开筛选弹窗
const rightClick = () => {
  popupRef.value.open();
};

// 打开日历弹窗
const handleCalendar = () => {
  calendarsRef.value.open();
};

// 选择日期
const confirmDate = (val) => {
  queryParams.completeTime = val.fulldate;
};

// 重置查询
const resetQuery = () => {
  queryParams.completeTime = "";
  popupRef.value.close();
  getList();
};

// 确认查询
const handleQuery = () => {
  popupRef.value.close();
  queryParams.pageNum = 1;
  getList();
};

// 获取列表数据
const getList = (change) => {
  // 获取提交失败数量
  let fails = uni.getStorageSync("offline-task-fail") || [];
  tabs.value[2].badge.value = fails.length;
  if (tabStatus.value === 0) {
    // 待提交
    let list = uni.getStorageSync("offline-task-submit") || [];
    list.forEach((item) => (item.offlineStatus = 0));
    dataList.value = list;
    total.value = list.length;
    moreStatus.value = "nomore";
  } else if (tabStatus.value === 1) {
    // 成功
    if (!change) {
      moreStatus.value = "loading";
      recordList(queryParams)
        .then((res) => {
          if (res.code == 200) {
            dataList.value =
              queryParams.pageNum == 1 ? res.rows : dataList.value.concat(res.rows);
            total.value = res.total;
          }
        })
        .finally(() => {
          if (total.value <= dataList.value.length) {
            moreStatus.value = "nomore";
          } else {
            moreStatus.value = "loadmore";
          }
        });
    }
  } else if (tabStatus.value === 2) {
    // 失败
    let list = uni.getStorageSync("offline-task-fail") || [];
    list.forEach((item) => (item.offlineStatus = 4));
    dataList.value = list;
    total.value = list.length;
    moreStatus.value = "nomore";
  }
};

// 提交
const handleSubmit = async (item) => {
  if (item.sumbiting) return;
  item.sumbiting = true;
  let promiseAll = [];
  for (let i = 0; i < item.imgUrl.length; i++) {
    const temp = item.imgUrl[i];
    if (temp.indexOf("_doc") !== -1) {
      let url = await uplaodImage(temp);
      item.imgUrl[i] = url;
      promiseAll.push(url);
    }
  }
  Promise.all(promiseAll).then(async () => {
    let data = Object.assign({}, item);
    data.imgUrl = data.imgUrl.join(",");
    data.offlineStatus = 1;

    const res = await recordAdd(data);
    if (res && res.code == 200) {
      uni.$emit("listSelectStateTask");
      let newList = uni.getStorageSync("offline-task-fail");
      newList = newList.filter((i) => i.completeTime !== item.completeTime);
      uni.setStorageSync("offline-task-fail", newList);

      let list = uni.getStorageSync("offline-task-list");
      if (!list.isFinish && res.data.isFinish) {
        list.isFinish = true;
        uni.setStorageSync("offline-task-list", list);
      }
      getList();
    } else {
      delete item.sumbiting;
      if (item.imgUrl.some((i) => i.indexOf("_doc") !== -1)) {
        saveFail(item, "图片上传失败");
      } else {
        saveFail(item);
      }
    }
  });
};

// 重新上传图片
const uplaodImage = (tempPath) => {
  return new Promise((resolve, reject) => {
    uni.getImageInfo({
      src: tempPath,
      success: ({ path }) => {
        commonUpload(path)
          .then((res) => {
            if (res.code == 200) {
              resolve(res.fileName);
            } else {
              resolve(tempPath);
            }
          })
          .catch(() => {
            resolve(tempPath);
          });
      },
      fail: (err) => {
        console.log("error", err);
        resolve(tempPath);
      },
    });
  });
};

// 保存错误信息
const saveFail = (item, failReason = "网络异常") => {
  let fails = uni.getStorageSync("offline-task-fail");
  if (fails) {
    fails = fails.filter((i) => i.completeTime !== item.completeTime);
    fails.push({ ...item, failReason });
  } else {
    fails = [{ ...item, failReason }];
  }
  uni.setStorageSync("offline-task-fail", fails);
  getList();
};
</script>
<style lang="scss" scoped>
.popup-content {
  width: 600rpx;
  height: 100%;
  position: relative;

  .date-box {
    height: 66rpx;
    padding: 12rpx;
    box-sizing: border-box;
    margin: auto 30rpx;
    background: #ffffff;
    border-radius: 8rpx;
    border: 2rpx solid #dedede;
    display: flex;
    align-items: center;

    .date {
      font-size: 28rpx;
      color: #bdbdbd;
      margin-left: 10rpx;
    }
  }

  .row-bottom {
    position: absolute;
    bottom: 0;
    width: 100%;
    display: flex;

    view {
      flex: 1;
    }
  }
}

:deep(.uv-popup__content__close--top-right) {
  top: calc(15px + var(--status-bar-height)) !important;
}
:deep(.uv-modal__title) {
  color: #333 !important;
}
:deep(.uv-modal__content__text) {
  color: #333 !important;
}
.offline-task-item {
  background-color: #fff;
  border-radius: 20rpx;
  margin: 30rpx;
  color: #999;
  box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
  &-status {
    position: absolute;
    right: 0;
    top: 0;
    font-size: 24rpx;
    padding: 0 24rpx 0 40rpx;
    border-bottom-left-radius: 50rpx;
    display: flex;
    align-items: center;
    height: 60rpx;
    image {
      width: 24rpx;
      height: 24rpx;
      margin-right: 10rpx;
    }
  }
  &-status-0 {
    color: #9ebaf1;
    background-color: #e3eeff;
  }
  &-status-1 {
    color: #4ea770;
    background-color: #e3fee3;
  }
  &-status-2 {
    color: #847cae;
    background-color: #ececf6;
  }
  &-status-3 {
    color: #ffa041;
    background-color: #fdf6e7;
  }
  &-status-4 {
    color: #ff0000;
    background-color: #fee3e3;
  }
  &-top {
    padding: 30rpx;
    > view {
      margin-bottom: 14rpx;
      font-size: 28rpx;
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
  &-title {
    color: #0a7fff;
    max-width: calc(100% - 220rpx);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  &-btn {
    height: 100rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #000;
    border-top: 1rpx solid #e5e5e5;
    font-size: 28rpx;
    &:active {
      background-color: #fafafa;
    }
  }
}
</style>
